import { DatePicker, Select } from 'antd'
import { isEmpty } from 'lodash-es'
import { useEffect, useState } from 'react'

import { PCS_COMPANION_PERIOD_ENUM } from '@/utils/enum'

const DatePickerWithSelect = ({
  disabled,
  value: nextValue,
  onChange,
  disabledDate,
  disabledSelect,
  className,
  selectProps = {},
}) => {
  const [comValue, setComValue] = useState()

  useEffect(() => {
    if (nextValue === comValue) return
    if (isEmpty(nextValue)) {
      setComValue()
    } else {
      setComValue(nextValue)
    }
  }, [nextValue])

  useEffect(() => {
    if (nextValue === comValue) return
    onChange(comValue)
  }, [comValue])

  const onDatePickerChange = date => {
    setComValue({
      ...comValue,
      datePicker: date,
      select: undefined,
    })
  }

  const onSelectChange = value => {
    setComValue({
      ...comValue,
      select: value,
    })
  }

  return (
    <div className={`flex ${className}`}>
      <div className='flex'>
        <DatePicker
          placeholder='请选择日期'
          disabled={disabled}
          disabledDate={disabledDate}
          value={comValue?.datePicker}
          onChange={onDatePickerChange}
        />
      </div>
      <Select
        disabled={!comValue?.datePicker || disabled}
        placeholder='请选择'
        className='ml10px'
        style={{ width: 90 }}
        value={comValue?.select}
        onChange={onSelectChange}
        {...selectProps}
      >
        {PCS_COMPANION_PERIOD_ENUM.options.map(({ value, label }) => (
          <Select.Option key={value} value={value} disabled={disabledSelect?.(value)}>
            {label}
          </Select.Option>
        ))}
      </Select>
    </div>
  )
}

export default DatePickerWithSelect
